#include "parkingmanager.h"
#include "ui_parkingmanager.h"  // 必须包含UI头文件
#include "carmainwindow.h"
#include "timemanager.h"
#include "databasemanager.h"

#include <QDateTime>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QScrollArea>
#include <QDebug>

// 构造函数
ParkingManager::ParkingManager(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ParkingManager),  // 现在可以正确分配
    m_mainWindow(qobject_cast<CarMainWindow*>(parent)),  // 初始化主窗口指针
    m_dbManager(DatabaseManager::instance())  // 初始化数据库管理器
{
    ui->setupUi(this);


    // 1. 创建滚动区域并设置属性
    QScrollArea *scrollArea = new QScrollArea;
    scrollArea->setWidgetResizable(true);  // 允许内容自适应
    scrollArea->setWidget(ui->groupBox_2);
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->verticalLayout_2->addWidget(scrollArea);

    // 初始化数据库
    initDatabase();

    // 连接 TimeManager 的时间更新信号
    connect(TimeManager::instance(), &TimeManager::timeUpdated,
            this, [this](const QString &timeStr) {
                ui->label_time->setText("时间: " + timeStr);
            });

    // 连接信号槽 - 车位数量变化
    connect(ui->spinBox_parking_slots, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &ParkingManager::updateSlotCount);

    updateSlotCount();  // 初始化显示车位信息
}

// 析构函数
ParkingManager::~ParkingManager()
{
    delete ui;
}

// 初始化数据库
void ParkingManager::initDatabase()
{
    // 检查并创建车位表（如果不存在）
    if (!m_dbManager->execute(
            "CREATE TABLE IF NOT EXISTS parking_slots ("
            "id INTEGER PRIMARY KEY AUTOINCREMENT,"
            "slot_number INTEGER NOT NULL UNIQUE,"
            "carid TEXT,"
            "enter_time TEXT)"))
    {
        qCritical() << "创建车位表失败:" << m_dbManager->lastError();
        return;
    }

    // 初始化车位数据
    auto countResult = m_dbManager->query("SELECT COUNT(*) FROM parking_slots");
    if (countResult.isEmpty() || countResult.first().value("COUNT(*)").toInt() == 0)
    {
        for (int i = 1; i <= totalSlots; ++i)
        {
            if (!m_dbManager->execute(
                QString("INSERT OR IGNORE INTO parking_slots (slot_number) VALUES (%1)").arg(i)))
            {
                qWarning() << "初始化车位数据失败:" << m_dbManager->lastError();
            }
        }
    }
}

// 更新车位数量
void ParkingManager::updateSlotCount()
{
    int newTotal = ui->spinBox_parking_slots->value();
    QVariantMap params;

    if(newTotal > totalSlots) // 处理新增车位
    {
        for(int i = totalSlots + 1; i <= newTotal; ++i)
        {
            m_dbManager->execute(
                QString("INSERT OR IGNORE INTO parking_slots (slot_number) VALUES (%1)").arg(i));
        }
    }
    else if(newTotal < totalSlots) // 处理减少车位(需先检查是否有车)
    {

        params["slot_number"] = newTotal;
        auto occupiedResult = m_dbManager->query(
            "SELECT COUNT(*) FROM parking_slots WHERE slot_number > :slot_number AND carid IS NOT NULL",
            params);

        if (!occupiedResult.isEmpty() && occupiedResult.first().value("COUNT(*)").toInt() > 0)
        {
            QMessageBox::warning(this, "警告", "不能减少车位数量，有车辆停放在将被移除的车位上");
            ui->spinBox_parking_slots->setValue(totalSlots);
            return;
        }

        m_dbManager->execute(
            QString("DELETE FROM parking_slots WHERE slot_number > %1").arg(newTotal));
    }

    // 设置初始车位数（从spinBox获取）
    totalSlots = newTotal;
    syncSlotsWithDatabase();
    setupSlots();

    // 显示剩余车位
    updateAvailableSlotsDisplay();
}

// 显示车位信息
void ParkingManager::showSlotInfo(int slotIndex)
{

    QVariantMap params;
    params["slot_number"] = slotIndex;

    auto slotInfo = m_dbManager->query(
        "SELECT carid, enter_time FROM parking_slots WHERE slot_number = :slot_number",
        params);

    if (slotInfo.isEmpty())
    {
        QMessageBox::warning(this, "错误", QString("无法获取车位 %1 的信息").arg(slotIndex));
        return;
    }

    const auto& info = slotInfo.first();
    QString carId = info["carid"].toString();
    QString enterTimeStr = info["enter_time"].toString();

    if (!carId.isEmpty())
    {
        // 计算停车时长和费用
        QDateTime enterTime = QDateTime::fromString(enterTimeStr);
        QDateTime currentTime = QDateTime::currentDateTime();
        int seconds = enterTime.secsTo(currentTime);

        // 使用主窗口的函数计算时长和费用
        QString durationStr = m_mainWindow->formatDuration(seconds);
        double fee = m_mainWindow->calculateFee(seconds, false);//默认不是会员

        // 显示信息对话框
        QString info = QString("车位 %1 信息:\n"
                              "车牌号: %2\n"
                              "入场时间: %3\n"
                              "停车时长: %4\n"
                              "当前费用: %5 元")
                       .arg(slotIndex)
                       .arg(carId)
                       .arg(enterTimeStr)
                       .arg(durationStr)
                       .arg(QString::number(fee, 'f', 2)); // 保留2位小数

        QMessageBox::information(this, "车位详情", info);
    }
    else
    {
        QMessageBox::information(this, "车位信息",
                                QString("车位 %1 当前空闲").arg(slotIndex));
    }
}

int ParkingManager::getMaxParkingSlots()
{
    return  totalSlots; // 返回spinBox值;
}

// 同步车位状态与curInfo表
void ParkingManager::syncSlotsWithDatabase()
{
    m_dbManager->execute("UPDATE parking_slots SET carid = NULL, enter_time = NULL");

    auto currentCars = m_dbManager->query("SELECT carid, enterTime FROM curInfo ORDER BY enterTime");

    int slotNumber = 1;
    for (const auto& car : currentCars)
    {
        if (slotNumber > totalSlots) break;

        QVariantMap params;
        params["carid"] = car["carid"];
        params["enter_time"] = car["enterTime"];
        params["slot_number"] = slotNumber;

        if (!m_dbManager->execute(
            "UPDATE parking_slots SET carid = :carid, enter_time = :enter_time "
            "WHERE slot_number = :slot_number", params))
        {
            qDebug() << "更新车位失败:" << m_dbManager->lastError();
        }

        slotNumber++;
    }

    if (currentCars.size() > totalSlots)
    {
        QMessageBox::warning(this, "警告",
            QString("当前停车场已满！有%1辆车无法分配车位").arg(currentCars.size() - totalSlots));
    }

    setupSlots();
    // 显示剩余车位
    updateAvailableSlotsDisplay();
}

// 设置车位布局
void ParkingManager::setupSlots()
{
    // 确保groupBox_2有布局
    if (!ui->groupBox_2->layout()) {
        QGridLayout *gridLayout = new QGridLayout(ui->groupBox_2);
        ui->groupBox_2->setLayout(gridLayout);
    }
    QGridLayout *layout = qobject_cast<QGridLayout*>(ui->groupBox_2->layout());

    // 清空现有按钮
    QList<QPushButton*> buttons = ui->groupBox_2->findChildren<QPushButton*>();
    foreach (QPushButton* button, buttons) {
        layout->removeWidget(button);
        delete button;
    }

    // 获取所有车位信息
    auto slotsInfo = m_dbManager->query("SELECT * FROM parking_slots ORDER BY slot_number");

    int columns = 6; // 每行6个车位
    int row = 0, col = 0;

    for (const auto& slot : slotsInfo) {
        int slotNumber = slot["slot_number"].toInt();
        // 跳过无效车位编号
        if (slotNumber <= 0 || slotNumber > totalSlots) continue;

        QPushButton *button = new QPushButton(ui->groupBox_2);
        button->setObjectName(QString("pushButton_slot%1").arg(slotNumber));
        button->setText(QString("车位%1").arg(slotNumber));
        button->setFixedSize(100, 60);
        button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

        QString carid = slot["carid"].toString();
        if (!carid.isEmpty()) {
            button->setStyleSheet("background-color: red; color: white;");
            button->setToolTip(QString("车牌: %1\n入场时间: %2")
                             .arg(carid)
                             .arg(slot["enter_time"].toString()));
        } else {
            button->setStyleSheet("background-color: green; color: white;");
            button->setToolTip("车位空闲");
        }

        // 计算行列位置
        row = (slotNumber-1) / columns;
        col = (slotNumber-1) % columns;

        layout->addWidget(button, row, col);

        connect(button, &QPushButton::clicked, [this, slotNumber]() {
            showSlotInfo(slotNumber);
        });
    }
}

// 前台设置按钮点击事件
void ParkingManager::on_beforesetbtn_clicked()
{
    this->hide();  // 隐藏当前窗口
    // this->close();// 或者直接关闭
}

// 触发剩余车位更新
void ParkingManager::updateAvailableSlotsDisplay()
{
    QVariantMap params;
    params["slot_number"] = totalSlots;
    auto availableResult = m_dbManager->query(
        "SELECT COUNT(*) FROM parking_slots WHERE carid IS NULL AND slot_number <= :slot_number",
        params);

    if (!availableResult.isEmpty()) {
        ui->label_available_slots->setText(
            QString("剩余车位: %1").arg(availableResult.first().value("COUNT(*)").toInt()));
    }
}
